import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test_qq/picture.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
class smallWorld extends StatefulWidget{

  const smallWorld({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState()=>smallWorldState();

}

class smallWorldState extends State<smallWorld>{
  bool hasMore = true;

  List  datas = [];
  var city = '绵阳';
  var tem = ''; // 实时温度
  var tem2 = ''; // 最低温度
  var tem1 = ''; // 最高温度
  var date = ''; // 日期
  var week = ''; // 星期
  var wea = '';  // 天气状况
  var win = '';  //风向
  var win_speed = ''; //风级
  var update_time = ''; // 更新时间
  var air_tips = ''; // 天气提示
  var air_level = ''; //空气质量
  var humidity = ''; // 湿度
  void initState(){
    // this.get();
    this._getData();

  }
  // 获取图片
  void _getData() async {
    final response = await http.get(Uri.parse(
        'https://v0.yiketianqi.com/api?unescape=1&version=v61&appid=55297681&appsecret=PZcXgN1m&city=${city}'
    ));
    Utf8Decoder decode = Utf8Decoder();
    Map<String, dynamic> result = jsonDecode(decode.convert(response.bodyBytes));
    print('result${result}');
    setState(() {
      tem = result['tem'];
      date = result['date'];
      week = result['week'];
      wea = result['wea'];
      update_time = result['update_time'];
      air_tips = result['air_tips'];
      win_speed = result['win_speed'];
      win = result['win'];
      air_level = result['air_level'];
      humidity = result['humidity'];
    });
    // print('data${result}');
    // Utf8Decoder decode = Utf8Decoder();
    // Map<String, dynamic> result = jsonDecode(decode.convert(response.bodyBytes));
    // datas = result['data'].map<Picture>((item) => Picture.fromJson(item)).toList();
    //
    // print('数据${datas}');
    // print('数据长度${datas.length}');
    // if(datas.length>0){
    //   setState(() {
    //     // 关闭加载
    //     this.hasMore = false;
    //     save(datas);
    //   });
    }
  TextEditingController enterCity = new TextEditingController();
  @override
  Widget build(BuildContext context) {
    return Container(
        child:Scaffold(
          resizeToAvoidBottomInset:  false,
          body: SingleChildScrollView(
            child: Column(
              children: [
                SizedBox(height: 30,),
                Card(
                    child: Column(
                      children: [
                        Row(
                          children: [
                            SizedBox(width: 10,),
                            SizedBox(
                              child:   TextField(
                                controller: enterCity,
                                decoration: InputDecoration(
                                  hintText: '城市名',
                                  filled: true,
                                  enabledBorder: OutlineInputBorder(
                                    borderSide: BorderSide(color: Colors.lightGreen),
                                    // borderRadius: BorderRadius.all(
                                    //   Radius.circular(15),
                                    // ),
                                  ),
                                  focusedBorder: OutlineInputBorder(
                                    borderSide: BorderSide(color:Colors.lightGreen),
                                    // borderRadius: BorderRadius.all(
                                    //   Radius.circular(15),
                                    // ),
                                  ),
                                ),
                              ),
                              width: 250,
                              height: 50,
                            ),
                            MaterialButton(
                                child: Text('搜   索',style: TextStyle(fontSize: 17),),
                                color: Colors.lightGreen,
                                height: 50,
                                onPressed:(){
                                  setState(() {
                                    city = enterCity.text;
                                  });
                                  this._getData();
                                }),
                          ],
                        ),
                        SizedBox(height: 30,),
                      ],
                    )
                ),
                Card(
                    child: Column(
                      children: [
                        Text(city == '' ? '请想要查询的输入城市名称' : city,
                            style: TextStyle(
                                color: Colors.lightGreen,
                                fontSize: 20
                            )),
                        SizedBox(height: 15,),
                        Row(
                          children: [
                            SizedBox(width: 10,),
                            Text('更新时间：${date}   ${week}   ${update_time}',style: TextStyle(
                                fontSize: 17,
                                color: Colors.grey
                            ),),
                          ],
                        ),
                        SizedBox(height: 15,),
                        Row(
                          children: [
                            SizedBox(width: 10,),
                            Text('实时温度：${tem}°C',style: TextStyle(
                                fontSize: 17
                            ),),
                            SizedBox(width: 90,),
                            Text('实时天气：${wea}',style: TextStyle(
                                fontSize: 17
                            ),)
                          ],
                        ),
                        SizedBox(height: 15,),
                        Row(
                          children: [
                            SizedBox(width: 10,),
                            Text('风向：${win}',style: TextStyle(
                                fontSize: 17
                            ),),
                            SizedBox(width: 127,),
                            Text('风级：${win_speed}',style: TextStyle(
                                fontSize: 17
                            ),)
                          ],
                        ),
                        SizedBox(height: 15,),
                        Row(
                          children: [
                            SizedBox(width: 10,),
                            Text('湿度：${humidity}',style: TextStyle(
                                fontSize: 17
                            ),),
                            SizedBox(width: 130,),
                            Text('空气质量：${air_level}',style: TextStyle(
                                fontSize: 17
                            ),)
                          ],
                        ),
                        SizedBox(height: 15,),
                        Row(
                          children: [
                            SizedBox(width: 10,),
                            Expanded(
                              child: Text('提示：${air_tips}',
                                style: TextStyle(
                                    fontSize: 17
                                ),),
                            )
                          ],
                        ),
                        SizedBox(height: 70,),
                      ],
                    )
                )

              ],
            ),
          )
        )


    );
  }

  }
  // 保存前5条数据
  // save(datas) async {
  //   List<String> url = [];
  //   List<String> c_t = [];
  //   List<String> fav_total = [];
  //   SharedPreferences prefs = await SharedPreferences.getInstance();
  //   for(int i = 0; i < 5; i++){
  //     url.add(datas[i].url);
  //     c_t.add(datas[i].c_t);
  //     fav_total.add(datas[i].fav_total);
  //   }
  //   prefs.setStringList('url', url);
  //   prefs.setStringList('c_t', c_t);
  //   prefs.setStringList('fav_total', fav_total);
  //   print('fav_total${fav_total}');
  // }
  // // 获取前5条数据
  // get() async {
  //   SharedPreferences prefs = await SharedPreferences.getInstance();
  //   List<Picture> urlList =[];
  //   var url = prefs.getStringList('url');
  //   var c_t = prefs.getStringList('c_t');
  //   var fav_total = prefs.getStringList('fav_total');
  //   for(int i=0; i< 5;i++){
  //     Picture pic = Picture();
  //     pic.url = url![i];
  //     pic.c_t = c_t![i];
  //     pic.fav_total = fav_total![i];
  //     urlList.add(pic);
  //   }
  //   // print('urlList${prefs.getStringList('url')}');
  //   setState(() {
  //     // 关闭加载
  //     datas = urlList;
  //     this.hasMore = false;
  //   });
  // }
// 下拉刷新
//   Future<void> onRefresh() async{
//     print("下拉刷新");
//     // 持续两秒
//     await Future.delayed(Duration(milliseconds:2000),(){
//       // _getData();
//     });
//   }
//   // 加载动画
//   Widget _getMoreWidget() {
//     // 如果还有数据
//     if(this.hasMore){
//       return Center(
//         child: Padding(
//           padding: EdgeInsets.all(10.0),
//           child: Row(
//             mainAxisAlignment: MainAxisAlignment.center,
//             crossAxisAlignment: CrossAxisAlignment.center,
//             children: <Widget>[
//               Text(
//                 '加载中',
//                 style: TextStyle(fontSize: 16.0),
//               ),
//               // 加载图标
//               CircularProgressIndicator(
//                 strokeWidth: 1.0,
//               )
//             ],
//           ),
//         ),
//       );
//     }else{
//       return Center(
//         child: Text("...到底咯..."),
//       );
//     }
//   }

  // String Checkurl(String url) {
  //   if (url.startsWith("http")) {
  //     return url;
  //   } else {
  //     return "http:" + url;
  //   }
  // }

